<?php

namespace App\Http\Controllers;

use App\Adv;
use App\BaiduForm;
use App\ChangfangdiConfig;
use App\Customer;
use App\Http\Requests\CustomerRequest;
use App\Jobs\Send;
use App\Lead;
use App\Notifications\JpushMsg;
use App\Notifications\JpushNotification;
use App\Project;
use App\ProjectUser;
use App\TengxunFrom;
use App\ToutiaoLead;
use App\Unit\UserUnit;
use App\User;
use App\UserProject;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{
    //
    public function send(Request $request)
    {
        $jpush = new JpushMsg();
        $jpush->setContent($request->desc);
        $jpush->setTitle($request->title);
        $this->dispatch(new Send($jpush));
    }

    public function kuaishou(Request $request)
    {
        $project_id = $request->project_id ?? 3;
        $create_user_id = $request->create_user_id ?? 1;
        Log::channel('kuaishou')->info('kuaishou', $request->all());
        $mobile = $request->input('phone');
        $name = $request->input('consumer_name');
        $lead = Lead::where('mobile', '=', $mobile)->where('project_id', '=', $project_id)->first();
        if ($lead) {
            return response()->json([
                'code' => 200
            ]);
        }
        $project = Project::find($project_id);
        if ($project->type == 0) {
            $userProject = new  UserProject();
            $owner_user_id = $userProject->current($project_id);
        } elseif ($project->type == 1) {
            $userProject = new ProjectUser();
            $owner_user_id = $userProject->current($project_id);
        } else {
            $owner_user_id = 1;
        }
        $lead = new Lead();
        $lead->create_user_id = $create_user_id;
        $lead->owner_user_id = $owner_user_id;
        $lead->next_time = 0;
        $lead->next_time = 0;
        $lead->customer_id = 0;
        $lead->source = '快手';
        $lead->is_transform = 0;
        $lead->name = $name ?? '未命名';
        $lead->mobile = $mobile;
        $lead->create_time = time();
        $lead->status = '潜在客户';
        $lead->project_id = $project_id;
        $lead->update_time = time();
        $lead->save();
        $jpush = new JpushMsg();
        $jpush->setContent('新增一条线索');
        $jpush->setTitle('新增一条线索');
        try {
            if ($owner_user_id == 1) {
                dispatch(new Send($lead));
            } else {
                $user = User::find($owner_user_id);
                if ($user) {
                    $user->notify(new \App\Notifications\LeadsNotification($lead));
                }
            }
        } catch (\Exception $exception) {

        }
        return response()->json([
            'code' => 200
        ]);

    }

    /**
     * 头条
     * @param Request $request
     */
    public function toutiaoForm(Request $request)
    {
        Log::info('头条信息', $request->all());
        $v = $request->all();
        if (isset($v['id'])) {
            $v['clue_id'] = $v['id'];
        }
        if (isset($v['app_name'])) {
            $v['appname'] = $v['app_name'];
        }
        $v['gender'] = 0;
        $project_id = $request->input('project_id', '');
        $project = Project::find($project_id);
        $create_user_id = $request->input('create_user_id', 1);
        $toutiao = ToutiaoLead::whereClueId($v['clue_id'])->first();
        if ($toutiao) {
            return [
                'code' => 1,
                'message' => "已经有了"
            ];
        }
        if (!$toutiao) {
            $toutiao = ToutiaoLead::create($v);
        }
        //查询lead是否有
        $lead = Lead::whereClueId($v['clue_id'])
            ->first();
        $leads = Lead::where('project_id', '=', $project_id)->where('mobile', '=', $toutiao->telphone)->where('create_time','>',Carbon::now()->addDays(-30)->getTimestamp())->orderByDesc('leads_id')->first();
        if ($leads){
            $config=[];
            if (ProjectUser::where('project_id',$project_id)->where('user_id',$leads->owner_user_id)->first()){
                $config['owner_user_id']=$leads->owner_user_id;
            }

        }
        if (!$lead) {
            $lead = new Lead();
            $lead->clue_id = $toutiao->clue_id;
            $lead->customer_id = 0;
            $lead->is_transform = 0;
            $lead->name = $toutiao->name;
            $lead->source = $toutiao->appname == '' ? '其他渠道' : $toutiao->appname;
            $lead->detail_address = $toutiao->location . $toutiao->address;
            $lead->remark = $toutiao->remark;
            // $moduleName = trim(preg_replace("/\\d+/", '', str_replace('电话', '', $toutiao->module_name)));
            $moduleName = $toutiao->module_name;
            $realnames = User::pluck('realname');
            $moduleUser = '';
            foreach ($realnames as $name) {
                if (strstr($moduleName, $name)) {
                    $moduleUser = $name;
                }
            }
            if (isset($config['owner_user_id'])) {
                $owner_user_id = $config['owner_user_id'];
            } elseif ($moduleName && $moduleUser) {
                $user = User::where('realname', $moduleUser)->first();
                $owner_user_id = $user->id;

            } elseif ($project->type == 0) {
                $userProject = new  UserProject();
                $owner_user_id = $userProject->current($project_id);
            } elseif ($project->type == 1) {
                $userProject = new ProjectUser();
                $owner_user_id = $userProject->current($project_id);
            } else {
                $owner_user_id = 1;
            }
            //查询adv_id
            $adv = Adv::whereAdvId($toutiao->adv_id)->first();
            if ($adv) {
                $create_user_id = $adv->user_id;
            } else {

            }
            //   project_id=24&create_user_id=9
            if ($project_id == 24 && $create_user_id == 9) {
                $create_user_id = 7;
            }
            if ($project_id == 23 || $project_id == 19) {
                $create_user_id = 66;
            }
            if ($create_user_id == 66) {
                $create_user_id = 7;
            }
            if ($project_id == 33 || $project_id == 30) {
                $create_user_id = 96;
            }
            if ($project_id == 16) {
                $create_user_id = 7;
            }

            //碧桂园林佳明
            if ($project_id == 29 && $create_user_id = 86) {
                $create_user_id = 111;
            }
            //高宏设置成刘康
            if ($project_id == 35) {
                $create_user_id = 150;
            }
            $lead->create_user_id = $create_user_id;
            $lead->mobile = $toutiao->telphone;
            $lead->owner_user_id = $owner_user_id;
            $lead->next_time = 0;
            if (isset($v['remark_dict']['需求面积'])) {
                $lead->crm_vfnlcv = $v['remark_dict']['需求面积'];
            }
            if (isset($v['remark_dict']['您的行业'])) {
                $lead->industry = $v['remark_dict']['您的行业'];
            }
            $lead->create_time = $toutiao->create_time;
            $lead->status = '潜在客户';
            $lead->project_id = $project_id;
            $lead->update_time = $toutiao->create_time;
            $lead->save();
            if (config('app.env') === 'production') {
                try {
                    if ($owner_user_id == 1) {
                        dispatch(new Send($lead));
                    } else {
                        $user = User::find($owner_user_id);
                        if ($user) {
                            $user->notify(new \App\Notifications\LeadsNotification($lead));
                        }
                    }
                } catch (\Exception $exception) {

                }
            }
            \Log::info('新增线索', $lead->toArray());
        }
        return [
            'code' => 0,
            'message' => 'success'
        ];
    }

    public function tengxunForm(Request $request)
    {
        $project_user = $request->project_user ?? '3_1';

        $project_user = explode('_', $project_user);
        $project_id = $project_user[0];
        if ($project_id == 21) {
            $project_id = 19;
        }
        $create_user_id = $project_user[1];
        \Log::info('user', $project_user);
        $data = json_decode($request->getContent(), true) ?? [];
        \Log::info('tengxundata' . $create_user_id, $request->all());
        $tengxun = TengxunFrom::whereLeadsId($data['leads_id'])->first();
        if ($tengxun) {
            return response()->json([
                'code' => 0,
                'message' => 'success',
                'data' => [[]]
            ]);
        }
        $tengxun = new TengxunFrom();
        $tengxun->leads_id = $data['leads_id'] ?? '';
        $tengxun->account_id = $data['account_id'] ?? '';
        $tengxun->account_type = $data['account_type'] ?? '';
        $tengxun->wechat_appid = $data['wechat_appid'] ?? '';
        $tengxun->agency_id = $data['agency_id'] ?? '';
        $tengxun->adgroup_id = $data['adgroup_id'] ?? '';
        $tengxun->adgroup_name = $data['adgroup_name'] ?? '';
        $tengxun->page_tools = $data['page_tools'] ?? '';
        $tengxun->leads_type = $data['leads_type'] ?? '';
        $tengxun->leads_name = $data['leads_name'] ?? '';
        $tengxun->leads_tel = $data['leads_tel'] ?? '';
        $tengxun->tel_location = $data['tel_location'] ?? '';
        $tengxun->leads_area = $data['leads_area'] ?? '';
        $tengxun->leads_email = $data['leads_email'] ?? '';
        $tengxun->leads_qq = $data['leads_qq'] ?? '';
        $tengxun->leads_wechat = $data['leads_wechat'] ?? '';
        $tengxun->leads_gender = $data['leads_gender'] ?? '';
        $tengxun->bundle = json_encode($data['bundle']) ?? '';
        $tengxun->leads_come_from = $data['leads_come_from'] ?? '';
        $tengxun->save();
        $lead = Lead::where('mobile', '=', $tengxun->leads_tel)->where('project_id', '=', $project_id)->first();
        if ($lead) {
            return response()->json([
                'code' => 0,
                'message' => 'success',
                'data' => [[]]
            ]);
        }
        $project = Project::find($project_id);
        if ($project->type == 0) {
            $userProject = new  UserProject();
            $owner_user_id = $userProject->current($project_id);
        } elseif ($project->type == 1) {
            $userProject = new ProjectUser();
            $owner_user_id = $userProject->current($project_id);
        } else {
            $owner_user_id = 1;
        }
        if ($project_id == 24 && $create_user_id == 9) {
            $create_user_id = 7;
        }
        if ($project_id == 23 || $project_id == 19) {
            $create_user_id = 66;
        }
        if ($project_id == 16) {
            $create_user_id = 7;
        }
        if ($project_id == 35) {
            $create_user_id = 147;
        }
        $lead = new Lead();
        $lead->create_user_id = $create_user_id;
        $lead->owner_user_id = $owner_user_id;
        $lead->next_time = 0;
        $lead->next_time = 0;
        $lead->customer_id = 0;
        $lead->source = '腾讯';
        $lead->is_transform = 0;
        $lead->detail_address = $tengxun->leads_area;
        $lead->name = $tengxun->leads_name == '' ? '未命名' : $tengxun->leads_name;
        $lead->mobile = str_replace('+86', '', $tengxun->leads_tel);
        $lead->create_time = time();
        $lead->status = '潜在客户';
        $lead->project_id = $project_id;
        $lead->update_time = time();
        $lead->crm_vfnlcv = $data['bundle']['需求面积'] ?? '';
        $lead->save();
        $jpush = new JpushMsg();
        $jpush->setContent('新增一条线索');
        $jpush->setTitle('新增一条线索');
        try {
            if ($owner_user_id == 1) {
                dispatch(new Send($lead));
            } else {
                $user = User::find($owner_user_id);
                if ($user) {
                    $user->notify(new \App\Notifications\LeadsNotification($lead));
                }
            }
        } catch (\Exception $exception) {

        }
        \Log::info('新增线索', $lead->toArray());
        return response()->json([
            'code' => 0,
            'message' => 'success',
            'data' => [[]]
        ]);
    }

    public function changfangdi(Request $request)
    {
        $name = $request->name ?? '未命名';
        $mobile = $request->mobile;
        $industry = $request->industry;
        //  $create_user_id=;
        $project_id = ChangfangdiConfig::find(1)->project_id ?? 3;
        $lead = Lead::where('mobile', '=', $mobile)->where('project_id', '=', $project_id)->first();
        if ($lead) {
            return 'success';
        }
        $lead = new Lead();
        $lead->customer_id = 0;
        $lead->is_transform = 0;
        if ($name) {
            $lead->name = $name;
        }
        if ($mobile) {
            $lead->mobile = $mobile;
        }
        $lead->source = '厂房帝';
        $project = Project::find($project_id);
        if ($project->type == 0) {
            $userProject = new  UserProject();
            $owner_user_id = $userProject->current($project_id);
        } elseif ($project->type == 1) {
            $userProject = new ProjectUser();
            $owner_user_id = $userProject->current($project_id);
        } else {
            $owner_user_id = 1;
        }
        $lead->create_user_id = ChangfangdiConfig::find(1)->create_user_id ?? 1;
        $lead->owner_user_id = $owner_user_id;
        $lead->next_time = 0;
        $lead->remark = $industry;
        $lead->create_time = time();
        $lead->status = '潜在客户';
        $lead->project_id = $project_id;
        $lead->update_time = time();
        $lead->save();
        $jpush = new JpushMsg();
        $jpush->setContent('新增一条线索');
        $jpush->setTitle('新增一条线索');
        try {
            if ($owner_user_id == 1) {
                dispatch(new Send($lead));
            } else {
                $user = User::find($owner_user_id);
                if ($user) {
                    $user->notify(new \App\Notifications\LeadsNotification($lead));
                }
            }
        } catch (\Exception $exception) {

        }
        \Log::info('新增线索', $lead->toArray());
        return 'success';
    }

    public function baiduForm(Request $request)
    {
        $project_id = $request->project_id ?? 3;
        $data = json_decode($request->getContent(), true) ?? [];
        $create_user_id = $request->create_user_id ?? 1;
        $owner_user_id = $request->owner_user_id ?? '';
        if ($project_id == 21) {
            $project_id = 19;
        }

        if ($project_id == 33 || $project_id == 30) {
            $create_user_id = 96;
        }

        if (isset($data['lead_id'])) {
            $baidu = BaiduForm::where('lead_id', $data['lead_id'])->first();
            if ($baidu) {
                return '线索重复';
            }
        }

        if (isset($data['phone'])) {
            $data['data'][] = ['name' => '电话', 'value' => $data['phone']];
            if ($data['phone']=='15217556668'){
                return  '重复提交';
            }

        }

        \Log::info('百度form', $data);
        $baiduForm = new BaiduForm();
        if (!isset($data['data'])) {
            $data['data'] = [];
        }
        if (isset($data['电话'])) {
            $data['data'][] = ['name' => '电话', 'value' => $data['电话']];
        }
        if (isset($data['姓名'])) {
            $data['data'][] = ['name' => '姓名', 'value' => $data['姓名']];
        }
        if (isset($data['称呼'])) {
            $data['data'][] = ['name' => '姓名', 'value' => $data['称呼']];
        }
        if (isset($data['面积'])) {
            $data['data'][] = ['name' => '面积', 'value' => $data['面积']];
        }
        if (isset($data['需求面积'])) {
            $data['data'][] = ['name' => '面积', 'value' => $data['需求面积']];
        }
        if (isset($data['地址'])) {
            $data['data'][] = ['name' => '地址', 'value' => $data['地址']];
        }

        $baiduForm->form_data = json_encode($data['data']);
        $baiduForm->site_id = $data['site_id'] ?? 1;
        $baiduForm->page_id = $data['page_id'] ?? 1;
        $baiduForm->lead_id = $data['lead_id'] ?? '';
        $baiduForm->save();
        if ($project_id == 24 && $create_user_id == 9) {
            $create_user_id = 7;
        }
        if ($create_user_id == 72) {
            $create_user_id = 86;
        }
        if ($project_id == 23 || $project_id == 19) {
            $create_user_id = 66;
        }
        //高宏设置成刘康
        //高宏设置成吴志刚
        if ($project_id == 35 || $project_id == 48) {
            $create_user_id = 161;
        }
        $name = collect($data['data'])->firstWhere('name', '=', '姓名')['value'] ?? '未命名';
        $mobile = collect($data['data'])->firstWhere('name', '=', '电话')['value'];
        $area = collect($data['data'])->firstWhere('name', '=', '面积')['value'];
        $dizhi = collect($data['data'])->firstWhere('name', '=', '地址')['value'];
        //$lead = Lead::where('mobile', '=', $mobile)->where('project_id', '=', $project_id)->orderByDesc('leads_id')->first();
        $lead = Lead::where('project_id', '=', $project_id)->where('mobile', '=', $mobile)->where('create_time','>',Carbon::now()->addDays(-30)->getTimestamp())->orderByDesc('leads_id')->first();
        /*  if ($lead) {
              return '线索重复';
          }*/
        if ($lead){
            if (ProjectUser::where('project_id',$project_id)->where('user_id',$lead->owner_user_id)->first()){
                $owner_user_id=$lead->owner_user_id;
            }
        }
        if (!$mobile){
            return  '手机号获取不到';
        }
        $lead = new Lead();

        $lead->customer_id = 0;
        $lead->is_transform = 0;
        if ($name) {
            $lead->name = $name;
        } else {
            $lead->name = '未命名';
        }
        if ($mobile) {
            $lead->mobile = $mobile;
        }
        if ($area) {
            $lead->crm_vfnlcv = $area;
        }
        $lead->source = '百度';

        $project = Project::find($project_id);

        if (!$owner_user_id){
            if ($project->type == 0) {
                $userProject = new  UserProject();
                $owner_user_id = $userProject->current($project_id);
            } elseif ($project->type == 1) {
                $userProject = new ProjectUser();
                $owner_user_id = $userProject->current($project_id);
            } else {
                $owner_user_id = 1;
            }
        }


        if ($project_id == 23 || $project_id == 19) {
            $create_user_id = 66;
        }

        if ($project_id == 16) {
            $create_user_id = 7;
        }
        $lead->create_user_id = $create_user_id;
        $lead->owner_user_id = $owner_user_id;
        $lead->next_time = 0;
        $lead->create_time = time();
        $lead->status = '潜在客户';
        $lead->project_id = $project_id;
        $lead->detail_address = $dizhi;
        $lead->update_time = time();
        $lead->save();
        $jpush = new JpushMsg();
        $jpush->setContent('新增一条线索');
        $jpush->setTitle('新增一条线索');
        try {
            if ($owner_user_id == 1) {
                dispatch(new Send($lead));
            } else {
                $user = User::find($owner_user_id);
                if ($user) {
                    $user->notify(new \App\Notifications\LeadsNotification($lead));
                }
            }
        } catch (\Exception $exception) {

        }
        \Log::info('新增线索', $lead->toArray());
        return 'success';
    }

    public function huaweiForm(Request $request, $project_id = 3, $create_user_id = 1)
    {

        $data = json_decode($request->getContent(), true) ?? [];

        \Log::info('华为from', $data);

        $baiduForm = new BaiduForm();
        $baiduForm->form_data = json_encode($data['data']);
        $baiduForm->site_id = $data['data']['site_id'];
        $baiduForm->save();
        $name = collect($data['data']['data'])->firstWhere('label', '=', '姓名')['value'];
        $mobile = collect($data['data']['data'])->firstWhere('label', '=', '电话')['value'];
        if (!$mobile) {
            $mobile = collect($data['data']['data'])->firstWhere('label', '=', '手机号')['value'];
        }
        $area = collect($data['data']['data'])->firstWhere('label', '=', '需求面积')['value'];
        $lead = Lead::where('mobile', '=', $mobile)->where('project_id', '=', $project_id)->first();
        if ($lead) {
            return 'success';
        }
        $lead = new Lead();
        $lead->customer_id = 0;
        $lead->is_transform = 0;
        if ($name) {
            $lead->name = $name;
        }
        if ($mobile) {
            $lead->mobile = $mobile;
        }
        if ($area) {
            $lead->crm_vfnlcv = $area;
        }
        $lead->source = '华为';
        if ($project_id == 21) {
            $project_id = 19;
        }

        $project = Project::find($project_id);
        if ($project->type == 0) {
            $userProject = new  UserProject();
            $owner_user_id = $userProject->current($project_id);
        } elseif ($project->type == 1) {
            $userProject = new ProjectUser();
            $owner_user_id = $userProject->current($project_id);
        } else {
            $owner_user_id = 1;
        }
        if ($project_id == 23 || $project_id == 16 || $project_id == 19) {
            $create_user_id = 66;
        }
        if ($project_id == 16) {
            $create_user_id = 7;
        }
        $lead->create_user_id = $create_user_id;
        $lead->owner_user_id = $owner_user_id;
        $lead->next_time = 0;
        $lead->create_time = time();
        $lead->status = '潜在客户';
        $lead->project_id = $project_id;
        $lead->update_time = time();
        $lead->save();
        $jpush = new JpushMsg();
        $jpush->setContent('新增一条线索');
        $jpush->setTitle('新增一条线索');
        try {
            if ($owner_user_id == 1) {
                dispatch(new Send($lead));
            } else {
                $user = User::find($owner_user_id);
                if ($user) {
                    $user->notify(new \App\Notifications\LeadsNotification($lead));
                }
            }
        } catch (\Exception $exception) {

        }
        \Log::info('新增线索', $lead->toArray());
        return 'success';
    }

    public function createCustomer(CustomerRequest $request)
    {
        $project_id = $request->project_id ?? 3;
        $name = $request->name;
        $mobile = $request->mobile;
        $area = $request->area;
        $create_user_id = $request->create_user_id;
        $owner_user_id = $request->owner_user_id;
        $lead = Lead::where('mobile', '=', $mobile)->where('project_id', '=', $project_id)->first();
        if ($lead) {
            return ['code' => 1];
        }
        $lead = new Lead();
        $lead->customer_id = 0;
        $lead->is_transform = 0;
        if ($name) {
            $lead->name = $name;
        }
        if ($mobile) {
            $lead->mobile = $mobile;
        }
        if ($area) {
            $lead->crm_vfnlcv = $area;
        }
        if ($project_id == 23 || $project_id == 16 || $project_id == 19) {
            $create_user_id = 66;
        }
        $lead->source = '华腾项目';
        $lead->create_user_id = $create_user_id;
        $lead->owner_user_id = $owner_user_id;
        $lead->next_time = 0;
        $lead->create_time = time();
        $lead->status = '潜在客户';
        $lead->project_id = $project_id;
        $lead->industry = $request->industry;
        $lead->remark = $request->remark;
        $lead->update_time = time();
        $lead->save();
        try {
            if ($owner_user_id == 1) {
                dispatch(new Send($lead));
            } else {
                $user = User::find($owner_user_id);
                if ($user) {
                    $user->notify(new \App\Notifications\LeadsNotification($lead));
                }
            }
        } catch (\Exception $exception) {

        }
        \Log::info('新增线索', $lead->toArray());
        return ['code' => 1];
    }
}
